const whiteList = ['/login']

module.exports = () => {
  return async function(ctx, next) {
    if (!whiteList.some(item => item === ctx.request.url)) {
      const token = ctx.request.header.authorization
      if (token) {
        try {
          const decoded = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret)
          if (decoded && decoded.message) {
            ctx.body = {
              code: 201,
              message: decoded.message
            }
          } else {
            ctx.userId = decoded.id
            await next()
          }
        } catch (error) {
          console.log(error);
          ctx.body = {
            code: 201,
            message: 'token 过期'
          }
        }
      } else {
        ctx.body = {
          code: 201,
          message: '未登录'
        }
      }
    } else {
      await next();
    }
  };
};
